﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Sita.Data.Repositories;
using Sita.Entities;


namespace Sita.MainModule.Services
{
    public class InvoiceService
    {
        InvoiceRepository InvoiceRepository;
        ReplacementService ReplacementService;
        DeliveryNoteService DeliveryNoteService;

        public InvoiceService()
        {
            InvoiceRepository = new InvoiceRepository();
            ReplacementService = new ReplacementService();
            DeliveryNoteService = new DeliveryNoteService();
        }

        public IList<Invoice> GetPaginatedInvoicesByBussinesUnitID(int businessUnitID, int pageIndex, int pageSize, string sortColumn, bool ascending, out int totalRows)
        {
            return InvoiceRepository.GetPaginatedByBusinessUnitID(businessUnitID, pageIndex, pageSize, sortColumn, ascending, out totalRows);
        }

        public Invoice GetInvoiceByIDWithItemsAndCustomer(int invoiceID)
        {
            Invoice invoice;
            invoice = InvoiceRepository.GetByIDWithItemsAndCustomer(invoiceID);

            foreach (InvoiceDeliveryNote idn in invoice.InvoiceDeliveryNotes)
            {
                foreach (DeliveryNoteReplacement dnr in idn.DeliveryNote.DeliveryNoteReplacements)
                {
                    idn.DeliveryNote.DeliveryNoteTotalPrice += dnr.TotalPrice;
                }

            }


            return invoice;
        }

        public void AddInvoice(Invoice invoice)
        {
            InvoiceRepository.Add(invoice);

            InvoiceRepository.StoreContext.Commit();
        }

        public Invoice GetInvoiceByIDWithItems(int invoiceID)
        {
            return InvoiceRepository.GetByIDWithItems(invoiceID);
        }

        public bool ModifyInvoice(Invoice invoice)
        {
            InvoiceRepository.Modify(invoice);

            InvoiceRepository.StoreContext.Commit();

            return true;
        }

        
        public string ValidateStockAndLock(int invoiceID)
        {
            bool LockReplacementSuccess;
            bool SaveReplacementSucess;
            LockReplacementSuccess = false;
            SaveReplacementSucess = false;
            Invoice LoadInvoice;
            string SuccessDeliveryNote = string.Empty;
            List<Replacement> LoadReplamentList;
            string Result = string.Empty;
            LoadReplamentList = new List<Replacement>();

            LoadInvoice = InvoiceRepository.GetByIDWithItems(invoiceID);
            
            //Por cada relación Invoice DeliveryNote
            foreach (var deliNoteItem in LoadInvoice.InvoiceDeliveryNotes)
            {
                SuccessDeliveryNote = DeliveryNoteService.ValidateStockAndLock(deliNoteItem.DeliveryNoteID);

                if (SuccessDeliveryNote != "SUCCESS" && SuccessDeliveryNote != "LOCKED")
                {
                    return SuccessDeliveryNote;
                }                
            }

            //Por cada Respuesto que no proviene de un Remito
            foreach (var item in LoadInvoice.InvoiceReplacements)
            {
                Replacement LoadReplacement = ReplacementService.GetReplacementByID(item.ReplacementID);

                if (LoadReplacement != null)
                {
                    if (LoadReplacement.Stock.HasValue)
                    {
                        if ((LoadReplacement.Stock.Value - item.Quantity) >= 0)
                        {
                            LoadReplacement.Stock = LoadReplacement.Stock.Value - item.Quantity;
                            LoadReplacement.LastSellDate = DateTime.Now;
                            LoadReplamentList.Add(LoadReplacement);
                            LockReplacementSuccess = true;
                        }
                        else
                        {
                            LockReplacementSuccess = false;
                            Result = string.Format("El repuesto {0} - {1} tiene un stock de : {2}. Stock Insuficiente.", LoadReplacement.ReplacementID, LoadReplacement.Name, LoadReplacement.Stock.Value);
                        }
                    }
                    else
                    {
                        LockReplacementSuccess = false;
                        Result = string.Format("El repuesto {0} - {1} no tiene stock definido.", LoadReplacement.ReplacementID, LoadReplacement.Name);
                    }
                }
                else
                {
                    LockReplacementSuccess = false;
                    Result = string.Format("El item {0} no pudo ser cargado.", item.ReplacementID);
                }

                if (!LockReplacementSuccess)
                {
                    return Result;
                }
                                
            }

            if (LockReplacementSuccess)
            {
                foreach (var item in LoadReplamentList)
                {
                    SaveReplacementSucess = ReplacementService.ModifyReplacement(item);

                    if (!SaveReplacementSucess)
                    {
                        Result = string.Format("No se pudo actualizar el repuesto {0} - {1}", item.ReplacementID, item.Name);
                        return Result;
                    }

                }

            }


            if (SaveReplacementSucess)
            {
                LoadInvoice.Blocked = true;
                this.ModifyInvoice(LoadInvoice);
                //this.ModifyDeliveryNote(LoadDeliveryNote);
                Result = "SUCCESS";
            }

            
           



            return Result;
        }


    }
}
